package com.sskjdata.cg.service.impl.sys;

import com.sskjdata.cg.dao.sys.SysUserMapper;
import com.sskjdata.cg.exception.IllegalParameterException;
import com.sskjdata.cg.po.sys.SysUser;
import com.sskjdata.cg.po.sys.SysUserExample;
import com.sskjdata.cg.service.impl.BaseServiceImpl;
import com.sskjdata.cg.service.sys.SysUserService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Descirption 用户service实现类
 * @Author Jason
 * @Date 2019/11/30/
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser findByUsername(String username) throws Exception {
        if(Strings.isNotBlank(username)){
            SysUserExample sysUserExample = new SysUserExample();
            SysUserExample.Criteria criteria = sysUserExample.createCriteria();
            criteria.andUsernameEqualTo(username);
            List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);
            if(sysUsers.size()>0){
                return sysUsers.get(0);
            }
        }
        return null;
    }

    @Override
    @Transactional
    public SysUser insert(SysUser sysUser) throws Exception {
        if(sysUser !=null){
            sysUserMapper.insertSelective(sysUser);
            return  sysUser;
        }
        return null;
    }


    @Override
    @Transactional
    public SysUser insertUser(Long orgId, String username, String password) throws Exception {
        if(orgId!=null
                && Strings.isNotBlank(username)
                && Strings.isNotBlank(password)
                ){
            SysUser sysUser = new SysUser();
            sysUser.setPassword(passwordEncoder.encode(password));
            sysUser.setUsername(username);
            sysUserMapper.insertSelective(sysUser);
            return sysUser;
        }
        throw new IllegalParameterException();
    }

	@Override
    @Transactional
	public SysUser updatePass(SysUser sysUser) {
		
		
		sysUser.setLastPasswordResetTime(new Date());
		sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword())); // 加密
		sysUserMapper.updateByPrimaryKeySelective(sysUser);
		
		return sysUser;
	}

    @Override
    public SysUser findUserByPramaryKey(Long id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }
}
